package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dao.DishDto;
import com.itheima.reggie.dao.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealDishServiceImpl extends ServiceImpl<SetmealDishMapper, SetmealDish> implements SetmealDishService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public SetmealDto getByIdWithFlavor(Long id) {

        Setmeal byId = setmealService.getById(id);

        SetmealDto setmealDto = new SetmealDto();


        BeanUtils.copyProperties(byId,setmealDto);

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(SetmealDish::getSetmealId,byId.getId());

        List<SetmealDish> list = setmealDishService.list(queryWrapper);

        System.out.println(list);

        setmealDto.setSetmealDishes(list);


        return setmealDto;
    }

    @Override
    public void updateWithFlavor(SetmealDto setmealDto) {
        //更新Setmeal表基本信息
        boolean updateById = setmealService.updateById(setmealDto);

        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
       setmealDishService.remove(queryWrapper);

        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
         setmealDishes  =  setmealDishes.stream().map((item) ->{
             item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
         setmealDishService.saveBatch(setmealDishes);
    }


}